<template>
	<!-- 我的/设置/修改密码 -->
	<view class="edit-pwd wrap-card">
		<u--input prefixIcon="lock-open" type="password" class="mb-20" v-model="form.oldPassword" placeholder="请输入旧密码"></u--input>
		<u--input prefixIcon="lock" class="mb-20" type="password" v-model="form.newPassword" placeholder="请输入新密码"></u--input>
		<u--input prefixIcon="checkbox-mark" type="password"  class="mb-20" v-model="form.reNewPwd" placeholder="请输入确认密码"></u--input>
		<!-- 底部操作 -->
		<view class="wrap-bottom-bar">
			<view class="bar-placeholder"></view>
			<view class="bar-content">
				<u-button :customStyle="btnStyle" :ripple="true" shape="circle" @click="submit">确定</u-button>
			</view>
		</view>
	</view>
</template>

<script>
import {UserApi} from '@/api/index.js'
import websocket from '@/utils/websocket/socket'
import websocketMixin from '@/utils/mixins/websocketMixin'
	export default {
		mixins: [websocketMixin],
		data(){
			return {
				form:{
					oldPassword:'',
					newPassword:'',
					reNewPwd:''
				},
				// 按钮配置
				btnStyle: {
					width: "90%",
					height: "75rpx",
					background: "linear-gradient(-45deg,#01906c,#34D399)",
					color: "#FFFFFF",
					fontSize: "30rpx",
				},
			}
		},
		computed:{
			// 禁用按钮
			disabled() {
				return this.form.oldPassword === '' || this.form.newPassword === '' || this.form.reNewPwd === '' 
			}
		},
		methods:{
			// 提交
			async submit() {
				// 验证
				if(this.form.oldPassword === '' || this.form.newPassword === '') return uni.$u.toast('请输入旧密码和新密码')
				const passwordReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/;
				if (!passwordReg.test(this.form.newPassword)) {
				    uni.$u.toast('密码必须包含至少一个字母、一个数字和一个特殊字符，并且长度至少为8个字符');
				    return;
				}
				if(this.form.newPassword !== this.form.reNewPwd) return uni.$u.toast('两次密码不一致')
				
				try{
					const res = await UserApi.resetPwd({
						oldPassword: this.form.oldPassword,
						newPassword: this.form.newPassword
					});
					if (res.code === 200) {
						uni.showToast({ title: '密码修改成功', icon: 'success' });
						UserApi.logout();
						// 清除全局数据
						const app = getApp();
						app.globalData.userId = null;
									
						// 清除本地存储
						uni.removeStorageSync('userId');
						uni.removeStorageSync('token'); 
						
						// 关闭 WebSocket
						websocket.closeSocket();
						this.$u.route('/pages/mine/login')
					} else {
						uni.showToast({ title: res.msg || '修改失败', icon: 'none' });
					}
				} catch (err) {
					console.error('修改密码失败：', err);
					uni.showToast({ title: '网络错误，请重试', icon: 'none' });
				}		
			}
		}
	}
</script>

<style lang="scss" scoped>
	.edit-pwd {
		
	}
</style>